package com.library.admin.modules.booktype.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.library.admin.modules.booktype.entity.BookType;
import com.library.admin.modules.booktype.vo.BookTypeVO;
import com.library.admin.modules.booktype.bo.BookTypePage;
import com.library.admin.modules.booktype.bo.BookTypeInsert;
import com.library.admin.modules.booktype.bo.BookTypeUpdate;
import com.library.admin.modules.booktype.mapper.BookTypeMapper;
import com.library.admin.modules.booktype.struct.BookTypeStructMapper;
import com.library.admin.modules.booktype.service.BookTypeService;
import com.library.common.exception.BaseException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import com.library.common.util.PageCovertUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


/**
 * @Author xyh
 * @Desc 图书分类表(BookType)表服务实现类
 * @Date 2023-10-05 09:46:51
 */

@Service("bookTypeService")
public class BookTypeServiceImpl extends ServiceImpl<BookTypeMapper, BookType> implements BookTypeService {

    @Resource
    private BookTypeStructMapper bookTypeStructMapper;

    @Override
    public List<BookType> bookTypeList() {
        List<BookType> list = baseMapper.selectList(new QueryWrapper<>());
        return list;
    }


    @Override
    public BookTypeVO queryById(Integer id) {
        BookType bookType = baseMapper.selectById(id);
        return bookTypeStructMapper.bookTypeToBookTypeVO(bookType);
    }

    @Override
    public boolean insert(BookTypeInsert bookTypeInsert) {
        BookType bookType = bookTypeStructMapper.insertToBookType(bookTypeInsert);
        checkBookTypeName(bookType);
        save(bookType);
        return true;
    }


    @Override
    public boolean update(BookTypeUpdate bookTypeUpdate) {
        BookType bookType = bookTypeStructMapper.updateToBookType(bookTypeUpdate);
        checkBookTypeName(bookType);
        updateById(bookType);
        return true;
    }

    private void checkBookTypeName(BookType bookType) {
        BookType type = lambdaQuery().eq(BookType::getTitle, bookType.getTitle())
                .select(BookType::getId)
                .last("limit 1")
                .one();
        if (type != null && !type.getId().equals(bookType.getId())) {
            throw new BaseException("该分类名称已经存在，不能重读添加！");
        }
    }

    @Override
    public boolean deleteById(Integer id) {
        return removeById(id);
    }

    @Override
    public List<BookTypeVO> getBookTypeTree() {
        List<BookType> list = list(new QueryWrapper<>());
        List<BookTypeVO> bookTypeVOS = bookTypeStructMapper.bookTypeToTypeListVO(list);

        List<BookTypeVO> bookTypes = buildBookTypeTree(bookTypeVOS);
        //排序
        //对子菜单排序
        if (CollUtil.isNotEmpty(bookTypes)) {
            bookTypes.forEach(m -> {
                if (CollUtil.isNotEmpty(m.getChildren())) {
                    Collections.sort(m.getChildren(), Comparator.comparing(BookTypeVO::getOrderNo));
                }
            });
            //对父菜单排序
            Collections.sort(bookTypes, Comparator.comparing(BookTypeVO::getOrderNo));
        }
        return bookTypes;
    }

    public List<BookTypeVO> buildBookTypeTree(List<BookTypeVO> list) {
        List<BookTypeVO> topBookType = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            // 首先找到所有顶层分类（parentId为null或0的分类）
            for (BookTypeVO vo : list) {
                if (vo.getParentId() == null || vo.getParentId() == 0) {
                    topBookType.add(vo);
                }
            }
            // 为顶层分类递归构建子分类树
            for (BookTypeVO vo : topBookType) {
                childBookTypeTree(vo, list);
            }
        }
        return topBookType;
    }

    public void childBookTypeTree(BookTypeVO parentBookType, List<BookTypeVO> topList) {
        List<BookTypeVO> childBookType = new ArrayList<>();
        // 找到当前父分类的子分类
        for (BookTypeVO vo : topList) {
            if (vo.getParentId() != null && vo.getParentId().equals(parentBookType.getId())) {
                childBookType.add(vo);
            }
        }
        // 递归构建子分类树
        for (BookTypeVO vo : childBookType) {
            childBookTypeTree(vo, topList);
        }
        //将子分类列表设置到父分类中
        if (CollUtil.isNotEmpty(childBookType)) {
            parentBookType.setChildren(childBookType);
        }
    }

}
